#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parse_code.h"
#include "map.h"
#define HASH_COUNT 16  /* hash table 默认长度 */ 

/* 解析字符串的 hash index */
int ParseIndex(char * name, int hash_count){
    int h=0;
    for (h=0; *name!=0; name++)
    {
        h <<= 8;
        h  += (unsigned char) *name;
        h  &= hash_count-1;
    }
    return h;
}



//初始化Map
Map *CreateMap(){
    Map * hash = (Map *)malloc(sizeof(Map));
    hash->node_count = 0;
    hash->hash_count = HASH_COUNT;
    hash->list = (Node **)calloc(HASH_COUNT, sizeof(Node*));
    return hash;
}


// 查找node
Node * FindKey(Node *n, char * key){
    Node *p;
    for(p=n; p; p=p->next) if( EQ(p->key, key) )  break;
    return p;
}

//查找node-list
Node * FindNode(Node ** list, char *key){
    Node *n =list(list, FindIndex(key, HASH_COUNT) );
    Node *p= FindKey(n, key );
    return p;
}



//赋值
int SetValue(Map *format, Value * new, char * key){
    int inx = FindIndex(key, HASH_COUNT);
    Node *n =list(format->list, inx);
    Node *p;
    
    for(p=n; p; p=p->next){
        if( EQ(p->key, key) ){
            p->data = new;
            return 1;
        }
    }

    Node * node = (Node *)malloc(sizeof(Node));
    node->key = key;
    node->data = new;
    if(n){
        // 如果链表存在,查找最后一个
        for(p=n; p; p=p->next) if(!p->next) break;

        p->next = node;
    }else{
        
        // 链表不存在, 当前节点为第1个
        list(format->list, inx) = node;
    }

    format->node_count++;
    return 0;
}

//取值
Value *GetValue(Map *format, char *key){
    Node *n = FindNode(format->list, key);
    if(n) {
        return n->data;
    }
    else{
        return NULL;
    }
}

void MapFree(Map *format){
    for(int i=0; i<HASH_COUNT; i++){
        Node *n =list(format->list, i);
        NodeFree(n);
    }
    free(format->list);
    free(format);
}
void NodeFree(Node *list){
    Node *p;
    for(p=list; p; p=p->next) free(p);
}